import { useChannels } from '@/utils/customHooks';
import { Card, Breadcrumb, Form, Select, Button, Input, Space, Radio, Upload, message } from 'antd'
import { Link } from 'react-router-dom'
import styles from "./index.module.scss";
import { useEffect, useState } from 'react';
import { PlusOutlined } from "@ant-design/icons"
import ReactQuill from 'react-quill';
import "react-quill/dist/quill.snow.css"
import { useDispatch } from 'react-redux';
import { addArticle, editArticle, getArticle } from '@/store/actions/article';
import { useHistory, useParams } from 'react-router-dom';

const Publish = () => {
    const params = useParams()
    const [form] = Form.useForm() // 得到form对象
    // 频道数据
    const dispatch = useDispatch()
    const history = useHistory()
    const channels = useChannels()
    const [type, setType] = useState(1)
    const [fileList, setFileList] = useState([])
    const onTypeChange = (e) => {
        setType(e.target.value)
        setFileList([]) // 只要切换图片  就将图片列表清空
    }
    useEffect(() => {
        const getArticleInfo = async () => {
            if (params.id) {
                // 获取文章详情的数据
                const { data } = await dispatch(getArticle(params.id))
                form.setFieldsValue({
                    title: data.title,
                    channel_id: data.channel_id,
                    content: data.content,
                }) // 设置表单的值
                // 设置 type fileList
                setType(data.cover.type)
                setFileList(data.cover.images.map((url) => ({ url })))
            } else {
                // 当前模式是新增情况下  默认清空上传列表 重置表单吧
                setType(1)
                setFileList([])
                // form重置表单
                form.resetFields() // 重新设置表单
            }
        }
        getArticleInfo()
    }, [dispatch, params, form])
    // 点击发表文章
    const onFinish = async (values, draft) => {
        // values是通过校验的数据
        if (type !== fileList.length) {
            return message.warning("封面类型和所上传图片不符合");
        }
        const data = {
            ...values,
            cover: {
                type,
                // 后台需要[string]类型
                images: fileList.map((item) => item?.response?.data?.url || item.url),
            }
        }
        if (params.id) {
            // 编辑场景
            await dispatch(editArticle({ id: params.id, ...data }, draft))
        } else {
            // 新增场景
            await dispatch(addArticle(data), draft) // 调用发布接口
        }
        message.success("操作成功")
        history.push('/home/article')
    }
    const saveDraft = async () => {
        try {
            const values = await form.validateFields() // 校验表单-返回表单的值
            onFinish(values, true) // 继续走原来的逻辑
        } catch (error) {
            // console.log("校验有问题")
        }
    }

    return (
        <div className={styles.root}>
            <Card
                title={
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to="/">首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <Link to="/article">内容管理</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>发布文章</Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form form={form} onFinish={onFinish} labelCol={{ span: 4 }}>
                    <Form.Item
                        label="文章标题："
                        name="title"
                        rules={[{ required: true, message: "文章标题不能为空" }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="所属频道："
                        name="channel_id"
                        rules={[{ required: true, message: "文章频道不能为空" }]}
                    >
                        <Select style={{ width: 400 }}>
                            {channels.map((item) => {
                                return (
                                    <Select.Option key={item.id} value={item.id}>
                                        {item.name}
                                    </Select.Option>
                                );
                            })}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面：">
                        <Radio.Group value={type} onChange={onTypeChange}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                        </Radio.Group>
                        {
                            (type === 1 || type === 3) && (<div style={{ marginTop: 16 }}>
                                <Upload
                                    name="image"
                                    listType="picture-card"
                                    action="http://toutiao.itheima.net/v1_0/upload"
                                    fileList={fileList}
                                    onPreview={() => { }}
                                    onChange={({ fileList }) => {
                                        setFileList(fileList)
                                    }}
                                >
                                    {fileList.length < type ? (
                                        <div>
                                            <PlusOutlined />
                                            <div style={{ marginTop: 8 }}>上传图片</div>
                                        </div>
                                    ) : null}
                                </Upload></div>)
                        }
                    </Form.Item>
                    <Form.Item label="文章内容" name="content" wrapperCol={{ span: 16 }} initialValue="" rules={[{ required: true, message: "文章内容不能为空" }]}>
                        <ReactQuill placeholder='请输入文章内容'></ReactQuill>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size='large' type="primary" htmlType='onsubmit'>发表文章</Button>
                            <Button size='large' onClick={saveDraft}>存入草稿</Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div >
    )
}

export default Publish
